package com.usian.wemedia.gateway.filter;

import com.usian.wemedia.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (request.getPath().toString().contains("/login/in")) return chain.filter(exchange);
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        ServerHttpResponse response = exchange.getResponse();
        if (StringUtils.isBlank(token)) {
            String json = "{\"errorMsg\":\"dont have token\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            if (i == 0 || i == -1) {
                Integer id = (Integer) claims.get("id");
                ServerHttpRequest newRequest = request.mutate().headers(httpHeaders ->
                        httpHeaders.add("userid", id + "")).build();
                exchange.mutate().request(newRequest).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            String json = "{\"errorMsg\":\"token is invalid\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
